package com.yimin.GenCode.imp;

import com.yimin.GenCode.InterfaceS.GenMybatisXmlAndServer;
import com.yimin.databaseS.DatabaseTableFieldEntity;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

@Service
public class GenMybatisXmlAndServerImp implements GenMybatisXmlAndServer {

    @Value("${gen.code.mybatisXmlPath}")
    String xmlPath;

    @Value("${gen.code.mybatisServerPath}")
    String serverPath;

    @Value("${gen.code.mybatisTemplateXmlPath}")
    String xmlTemplatePath;

    @Value("${gen.code.comPath}")
    String comPath;


    @Override
    public String genMybatisXml(List<DatabaseTableFieldEntity> fieldEntityList, String tableName) throws FileNotFoundException {

        /**
         * 计算当前表需要几个Sql 语句 1 + 2 + 1 + 2 =6个语句
         * 增加 1 删除 2 单个删除 批量删除 修改 1 查询 2 单个 id查询 条件查询
         *
         */

        /**
        * 增加语句模板
         */
        String AddSqlTe="<insert id=\""+"Add"+humpTransition(tableName)+"\"  parameterType=\""+comPath+".entity.Entity"+humpTransition(tableName)+"\"  >\n" +
                "   insert into "+tableName+AddSqlTeContentGen(fieldEntityList)+"   \n" +
                "</insert> \n";

        /**
         * 单个删除语句模板
         */
        String DeleteSqlSingleTe="<delete id=\""+"Delete"+humpTransition(tableName)+"\"  parameterType=\""+comPath+".entity.Entity"+humpTransition(tableName)+"\" >\n" +
                "   delete from "+tableName+"  "+DeleteSqlSingleTeContent(fieldEntityList)+"\n" +
                "</delete> \n";

        /**
         * 批量删除语句模板  这个暂时不做
         */
        String DeleteSqlBatchTe="<delete id=\"\">\n" +
                "        \n" +
                "</delete> \n";




        /**
         * 修改语句模板
         */
        String UpdateSqlTe="<update id=\""+"Update"+humpTransition(tableName)+"\" parameterType=\""+comPath+".entity.Entity"+humpTransition(tableName)+"\">\n" +
                "   update   "+tableName+" "+UpdateSqlTeContent(fieldEntityList)+"\n"+
                "</update> \n";




        /**
         * 单个id查询 语句 模板
         */
        String querySqlSingleTe="<select id=\""+"Query"+humpTransition(tableName)+"\" parameterType=\""+comPath+".entity.Entity"+humpTransition(tableName)+"\">\n" +
                "   select * from "+ tableName +" where "+ querySqlSingleTeContent(fieldEntityList)+"\n"+
                "</select>\n";


        /**
         *
         * 条件查询语句 模板
         *
         */
        String conditionQuerySqlTe="<select id=\"\">\n" +
                "        \n" +
                "</select> \n";



        String namespace=comPath+".mapper."+"MybatisServer"+humpTransition(tableName);


        //开始写入文件
        String xmlTeContent=readFileToString(xmlTemplatePath);

        String ContentText=AddSqlTe+"\n"+DeleteSqlSingleTe+"\n"+UpdateSqlTe+"\n"+querySqlSingleTe;
        xmlTeContent= xmlTeContent.replace("${mapperContent}",ContentText);
        xmlTeContent= xmlTeContent.replace("${namespace}",namespace);





        return xmlTeContent;
    }

    @Override
    public String genMybatisServer(List<DatabaseTableFieldEntity> fieldEntityList, String tableName) {

       String headFileContent="package com.yimin.mapper;\n" +
               "\n" +
               "import com.yimin.entity.Entity" +humpTransition(tableName)+";\n"+
               "\n" +
               "import org.apache.ibatis.annotations.MapKey;\n" +
               "import org.apache.ibatis.annotations.Mapper;\n" +
               "import org.mybatis.spring.annotation.MapperScan;\n" +
               "\n" +
               "import java.util.List;\n" +
               "import java.util.Map;" +
               "\n" +
               "@Mapper\n" +
               "public interface MybatisServer"+humpTransition(tableName)+" {\n";

       String endingFileContent="}";

       String AddSignSqlInterface="@MapKey(\"id\")\n" +
               "String Add"+humpTransition(tableName)+"(Entity"+humpTransition(tableName)+" "+"entity"+humpTransition(tableName)+");\n";

       String deleteSignInterface="@MapKey(\"id\")\n" +
               "String Delete"+humpTransition(tableName)+"(Entity"+humpTransition(tableName)+" "+"entity"+humpTransition(tableName)+");\n";

       String updateSignInterface="@MapKey(\"id\")\n" +
               "String Update"+humpTransition(tableName)+"(Entity"+humpTransition(tableName)+" "+"entity"+humpTransition(tableName)+");\n";

       String querySignInterface="@MapKey(\"id\")\n" +
               "List<Eneity"+humpTransition(tableName)+"> Query"+humpTransition(tableName)+"(Entity"+humpTransition(tableName)+" "+"entity"+humpTransition(tableName)+");\n";



        return headFileContent + AddSignSqlInterface +deleteSignInterface +updateSignInterface +querySignInterface +endingFileContent;
    }




    public static String readFileToString(String fileName) throws FileNotFoundException {
        String encoding = "UTF-8";
        File file =  ResourceUtils.getFile(fileName);
        Long filelength = file.length();
        byte[] filecontent = new byte[filelength.intValue()];
        FileInputStream in=null;
        try {
            in = new FileInputStream(file);
            in.read(filecontent);
            return new String(filecontent, encoding);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
        }
    }


    public static String writeFileByString(String fileName,String content) throws FileNotFoundException {
        String encoding = "UTF-8";
       System.err.println(fileName);
       System.err.println(content);
        try {


            File file=new File(fileName);

            if(!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }


            if(!file.exists()){
                file.createNewFile();
            }

            FileWriter fw = new FileWriter(file);

            fw.write(content);
            fw.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

         return "写入成功";
    }

    public String AddSqlTeContentGen(List<DatabaseTableFieldEntity> fieldEntityList){
                  String re="";

        AtomicReference<String> f1= new AtomicReference<>("(");
        AtomicInteger index= new AtomicInteger();
        fieldEntityList.forEach(item->{
            if(index.get() < fieldEntityList.size()-1){
                f1.set(f1 + item.getFieldName()+",");
            }else{
                f1.set(f1 + item.getFieldName());
            }
          index.getAndIncrement();
        });
        f1.set(f1+")");

        AtomicReference<String> f2= new AtomicReference<>("VALUES(");
        AtomicInteger index2= new AtomicInteger();
        fieldEntityList.forEach(item->{
            if(index2.get() < fieldEntityList.size()-1){

                if(item.getFileDataType().equals("INTTYPE")){
                    f2.set(f2 +"${"+humpTransition(item.getFieldName())+"},");
                }else{
                    f2.set(f2 +"#{"+humpTransition(item.getFieldName())+"},");
                }


            }else{
                if(item.getFileDataType().equals("INTTYPE")){
                    f2.set(f2 +"${"+humpTransition(item.getFieldName())+"}");
                }else{
                    f2.set(f2 +"#{"+humpTransition(item.getFieldName())+"}");
                }
            }
            index2.getAndIncrement();
        });
        f2.set(f2+")");

        return f1 + " " +f2;
    }

    String DeleteSqlSingleTeContent(List<DatabaseTableFieldEntity> fieldEntityList){

        AtomicReference<String> re= new AtomicReference<>("");

        fieldEntityList.forEach(item->{

            /**
             * 这表示当前字段是主键
             */
            if(item.getFileType().equals("key")){
                if(item.getFileDataType().equals("INTTYPE")){
                    re.set("where " + item.getFieldName() + " = ${" + humpTransition(item.getFieldName()) + "}");
                }else{
                    re.set("where " + item.getFieldName() + " = #{" + humpTransition(item.getFieldName()) + "}");
                }

            }

        });

        return re.get();

    }

    String UpdateSqlTeContent(List<DatabaseTableFieldEntity> fieldEntityList){

       AtomicReference<String> re= new AtomicReference<>("set ");

       AtomicReference<String> idName= new AtomicReference<>("");
        AtomicReference<String> idType= new AtomicReference<>("");

       AtomicInteger indexX= new AtomicInteger();

        fieldEntityList.forEach(item->{
            if(item.getFileType().equals("key")){

                idName.set(item.getFieldName());
                idType.set(item.getFileDataType());
            }
        });



        fieldEntityList.forEach(item->{
            if(item.getFileType().equals("foreignKey")){


            }else{
                if(item.getFileDataType().equals("INTTYPE")){

                    if(indexX.get() < fieldEntityList.size()-1){

                        re.set(re+item.getFieldName()+"=${"+humpTransition(item.getFieldName())+"},");

                    }else{
                        re.set(re+item.getFieldName()+"=${"+humpTransition(item.getFieldName())+"}");

                    }

                }else{

                    if(indexX.get() < fieldEntityList.size()-1){

                        re.set(re+item.getFieldName()+"=#{"+humpTransition(item.getFieldName())+"},");

                    }else{
                        re.set(re+item.getFieldName()+"=#{"+humpTransition(item.getFieldName())+"}");

                    }

                }
                indexX.getAndIncrement();


            }



        });

        if(idType.equals("INTTYPE")){
            return re.get()+" where "+idName+"=${"+humpTransition(idName.get())+"}";
        }else{
            return re.get()+" where "+idName+"=#{"+humpTransition(idName.get())+"}";
        }



    };



    String querySqlSingleTeContent(List<DatabaseTableFieldEntity> fieldEntityList){

        AtomicReference<String> re= new AtomicReference<>(" ");

        AtomicReference<String> idName= new AtomicReference<>(" ");

        AtomicReference<String> idType= new AtomicReference<>(" ");

        fieldEntityList.forEach(item->{

            if(item.getFileType().equals("key")){
                idName.set(item.getFieldName());
                idType.set(item.getFileDataType());
            }

        });

        if(idType.equals("INTTYPE")){


            re.set(idName+"=${"+humpTransition(idName.get())+"}");

        }else{
            re.set(idName+"=#{"+humpTransition(idName.get())+"}");
        }

        return re.get();

    };



    String conditionQuerySqlTeContent(List<DatabaseTableFieldEntity> fieldEntityList){
        AtomicReference<String> re= new AtomicReference<>(" ");

        AtomicReference<String> idName= new AtomicReference<>(" ");

        AtomicReference<String> idType= new AtomicReference<>(" ");

        fieldEntityList.forEach(item->{

            if(item.getFileDataType().equals("foreignKey")){
                idName.set(item.getFieldName());
                idType.set(item.getFileDataType());
            }

        });






        return re.get();
    }

    /**
     * 转换驼峰的方法
     * @param stringS
     * @return
     */
    public String humpTransition(String  stringS){

        String[] StringSz=stringS.split("_");

        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < StringSz.length; i++) {
            String word = StringSz[i];
            if (i == 0) {
                word = word.isEmpty() ? word : word.toLowerCase();
            } else {
                word = word.isEmpty() ? word : Character.toUpperCase(word.charAt(0)) + word.substring(1).toLowerCase();
            }
            builder.append(word);
        }
        return builder.toString();

    }


}
